package br.com.hstar.client.cliente.cheque;

import java.util.Iterator;
import java.util.List;

import br.com.hstar.client.ServiceFactory;
import br.com.hstar.client.cliente.cliente.ClienteUI;
import br.com.hstar.client.util.FormPanel;
import br.com.hstar.client.util.HstarDialogBox;
import br.com.hstar.client.util.HstarUserException;
import br.com.hstar.client.util.calendar.DatePicker;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

public class ChequeEditPanel extends FormPanel {

	private Button incluir;
	private Button cancelar;
	private Button excluir;
	
	private ListBox cliente;
	private TextBox valor;
	private DatePicker dataEmissao;
	private DatePicker dataDeposito;
	private TextBox numeroCheque;
	private TextBox banco;
	private TextBox agencia;
	private CheckBox devolvido;
	private ChequeClienteUI chequeUI;

	public ChequeEditPanel(String _title) {
		super(_title);
		chequeUI = new ChequeClienteUI();
		init(true);
	}
	
	public ChequeEditPanel(String _title, Long id) {
		super(_title);
		chequeUI = new ChequeClienteUI();
		chequeUI.setId(id);
		init(false);
		ServiceFactory.createChequeService().retrieveById(id, new RetrieveAsyncCallback());
	}
	
	
	
	//Methods -------------------------------------------------------------------
	
	private void init(boolean isNew) {

		cliente 		= addListBox("Cliente", true);
		ServiceFactory.createClienteService().listAll(new ListAllClientesAsyncCallback());
		valor			= addTextBox("Valor", 10, 10, "");
		dataEmissao 	= addCalendar("Data de Emissão");
		dataEmissao.setReadOnly(true);
		dataDeposito 	= addCalendar("Data de Depósito");
		dataDeposito.setReadOnly(true);
		numeroCheque	= addTextBox("Número do Cheque", 20, 20, "");
		banco	 		= addTextBox("Banco", 35, 40, "");
		agencia 		= addTextBox("Agência", 35, 40, "");
		devolvido		= addCheckBox("Devolvido", false);
		
		
		
		if(isNew) {
			incluir  = addButton("Incluir");
			cancelar = addButton("Cancelar");
		} else {
			incluir  = addButton("Alterar");
			cancelar = addButton("Cancelar");
			excluir = addButton("Excluir");
			excluir.addClickListener(new ClickListener() {
				public void onClick(Widget sender) {
					ServiceFactory.createChequeService().delete(chequeUI.getId(), new DeleteAsyncCallback());
				}
			});
		}
		
		incluir.addClickListener(new ClickListener() {
			public void onClick(Widget sender) {
				 try {
					copyData();
					ServiceFactory.createChequeService().saveOrUpdate(chequeUI, new SaveAsyncCallback());
				} catch (HstarUserException e) {					
					new HstarDialogBox("Cheque",e.getMessage());
				}
				
			}
		});
		cancelar.addClickListener(new ClickListener() {
			public void onClick(Widget sender) {
				RootPanel.get("boxContent").clear();
				RootPanel.get("boxContent").add(new ChequeListPanel("Cheque"));
			}
		});
		
	}

	private void copyData() throws HstarUserException {
		
		String msgErro = "";
		
		if(cliente.getSelectedIndex() < 1)
		{			
			msgErro = " - Selecione um cliente <br>";
		}
		
		try
		{
			chequeUI.setValor(new Double(valor.getText().trim()));
		}catch(NumberFormatException ex)
		{	
			msgErro += " - Valor inválido <br>";
		}
		
		
		if(dataEmissao.getText().trim() == "")
		{			
			msgErro += " - Selecione a data de emissão <br>";
		}
		
		if(dataDeposito.getText().trim() == "")
		{			
			msgErro += " - Selecione a data de depósito <br>";
		}
		
		if(numeroCheque.getText().trim() == "")
		{
			msgErro += " - Digite o número do cheque <br>";
		}
		
		if(banco.getText().trim() == "")
		{
			msgErro += " - Digite o número do banco <br>";
		}
		
		if(agencia.getText().trim() == "")
		{
			msgErro += " - Digite o número da agência <br>";
		}
		
		if(msgErro != "")
		{
			throw new HstarUserException(msgErro);			
		}
		
		chequeUI.setCliente(
				new ClienteUI(new Long(cliente.getValue(cliente.getSelectedIndex()))));
		
		chequeUI.setDataEmissao(dataEmissao.getSelectedDate());
		chequeUI.setDataDeposito(dataDeposito.getSelectedDate());
		chequeUI.setNumeroCheque(numeroCheque.getText().trim());
		chequeUI.setBanco(banco.getText().trim());
		chequeUI.setAgencia(agencia.getText().trim());
		chequeUI.setDevolvido(devolvido.isChecked());
		

		
	}

	// INNER CLASSES ----------------------------------------------------------------
	private class SaveAsyncCallback implements AsyncCallback {
		public void onFailure(Throwable caught) {
			if(caught instanceof HstarUserException)
			{					
				new HstarDialogBox("Cheque",caught.getMessage());
			}
		}

		public void onSuccess(Object result) {
			RootPanel.get("boxContent").clear();
			RootPanel.get("boxContent").add(new ChequeListPanel("Cheque"));
		}
	}
	
	private class DeleteAsyncCallback implements AsyncCallback {
		public void onFailure(Throwable caught) {
			Window.alert("ERRO - Cheque edit panel");
		}

		public void onSuccess(Object result) {
			RootPanel.get("boxContent").clear();
			RootPanel.get("boxContent").add(new ChequeListPanel("Cheque"));
		}
	}
	
	//carrega os campos. Usado para quando está editando
	private class RetrieveAsyncCallback implements AsyncCallback {
		public void onFailure(Throwable caught) {
			Window.alert("ERRO - Cheque edit panel");
		}

		public void onSuccess(Object result) {
			ChequeClienteUI cheque = (ChequeClienteUI)result;

			valor.setText(cheque.getValor().toString().trim());
			dataEmissao.setText(cheque.getDataEmissao());
			dataDeposito.setText(cheque.getDataDeposito());
			numeroCheque.setText(cheque.getNumeroCheque().trim());
			banco.setText(cheque.getBanco().trim());
			agencia.setText(cheque.getAgencia().trim());
			devolvido.setChecked(cheque.isDevolvido());
			
			
			
			if (cliente != null && cheque.getId() != null) {
				for(int i = 0; i < cliente.getItemCount(); i++) {
					if(cliente.getItemText(i).equals(cheque.getCliente().getValue(1))) {
						cliente.setSelectedIndex(i);
						break;
					}
				}
			}
			
			
		}
	}
	
//	lista todos os clientes para colocar no listbox
	private class ListAllClientesAsyncCallback implements AsyncCallback {
		public void onFailure(Throwable caught) {
			Window.alert("ERRO ao listar Cheque");
		}

		public void onSuccess(Object result) {
			List clientes = (List) result;
			for (Iterator iter = clientes.iterator(); iter.hasNext();) {
				ClienteUI clienteUI = (ClienteUI) iter.next();
				cliente.addItem(clienteUI.getNome(), clienteUI.getId().toString());				
			}
		}
	}

}      